package com.wentao.mall.api

import com.wentao.mall.dao.OperatorDao
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.Authentication
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RequestMapping("/api")
@RestController
class ApiController(
    val operatorDao: OperatorDao
) {

    @GetMapping("/currentUser")
    fun currentUser(@Autowired authentication: Authentication?): CurrentUser? {
        if (authentication == null) return CurrentUser(name = "test", access = listOf("2", "3"), userid = 1)

        val name = authentication.name
        val dbUser = operatorDao.findByUsername(name)!!
        val authorities = authentication.authorities.map { it.authority }


        return CurrentUser(name = name, access = authorities, userid = dbUser.id)
    }

    data class CurrentUser(
        val userid: Int,
        val name: String,
        val access: List<String>
    )

    @GetMapping("/403")
    fun error403(): Result {
        return Result.error("403, must login")
    }

    @GetMapping("/logout/success")
    fun logoutSuccess(): Result {
        return Result.success()
    }

    @GetMapping("/login/success")
    fun loginSuccess(): LoginResult {
        return LoginResult(status = "ok")
    }

    @GetMapping("/login/fail")
    fun loginFail(): LoginResult {
        return LoginResult(status = "error")
    }

    data class LoginResult(
        val status: String,
        val currentAuthority: String? = null,
        val type: String = "account"
    )
}